package com.wangshuqi.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

    // 连接池相关配置
    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(100); // 最大连接数
        jedisPoolConfig.setMaxIdle(100); // 最大空闲数 = 最大连接数
        jedisPoolConfig.setMinIdle(10); // 最小空闲连接数
        jedisPoolConfig.setMaxWaitMillis(2000); // 最长等待时间 默认0 无限等待
        return jedisPoolConfig;
    }

    @Bean
    public JedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        // Redis单机远程服务访问
        RedisStandaloneConfiguration standaloneConfiguration
                = new RedisStandaloneConfiguration("127.0.0.1", 6379);
        standaloneConfiguration.setPassword("wsq123");
        // new JedisConnectionFactory(standaloneConfiguration);

        // Redis集群访问
        // RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
        // new JedisConnectionFactory(clusterConfiguration);

        // 配置Jedis连接池（这里需要在项目配置里配置语言级别为8）
        JedisClientConfiguration configuration = JedisClientConfiguration.builder()
                .usePooling()
                .poolConfig(jedisPoolConfig)
                .build();
        return new JedisConnectionFactory(standaloneConfiguration, configuration);
    }

    @Bean
    public RedisTemplate redisTemplate(JedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置redis序列化方式
//        redisTemplate.setDefaultSerializer(new Jackson2JsonRedisSerializer(Object.class));
        redisTemplate.setKeySerializer(new StringRedisSerializer()); // 设置key的序列化方式
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));// 设置value序列化方式

        // redis hash类型序列化
        redisTemplate.setHashKeySerializer(new Jackson2JsonRedisSerializer(Object.class));
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
        return redisTemplate;
    }
}
